import os
import re
from urllib.parse import quote, unquote
from flask import send_from_directory, Response, request
import mimetypes
from config import MOVIES_FOLDER

class VideoCore:

    @staticmethod
    def get_video_files(directory):
        video_files = []
        for root, dirs, files in os.walk(directory):
            relative_root = os.path.relpath(root, directory).replace("\\", "/")
            if relative_root == ".":
                relative_root = ""

            for file in files:
                if file.lower().endswith(('.mp4', '.avi', '.mkv', '.mov')):
                    # 修正路径拼接方式
                    video_path = os.path.join(relative_root, file).replace("\\", "/").lstrip('/')
                    video_id = quote(video_path)
                    video_files.append({
                        'id': video_id,
                        'name': file,
                        'folder': relative_root if relative_root else "根目录"
                    })
        return video_files

    @staticmethod
    def video(video_path):
        video_path = unquote(video_path)
        base_dir = os.path.abspath(MOVIES_FOLDER)
        target_path = os.path.join(base_dir, video_path)
        
        if not os.path.exists(target_path):
            return "File not found", 404
        
        # 获取文件大小
        file_size = os.path.getsize(target_path)
        
        # 获取MIME类型
        mime_type, _ = mimetypes.guess_type(target_path)
        if not mime_type:
            mime_type = 'video/mp4'
        
        # 缓冲区大小
        buffer_size = 1024 * 8  # 8KB缓冲区
        
        # 检查是否有Range请求头
        range_header = request.headers.get('Range', None)
        
        # 默认从文件开始处读取
        start_byte = 0
        end_byte = file_size - 1
        
        # 处理Range请求头
        if range_header:
            range_match = re.search(r'bytes=(\d+)-(\d*)', range_header)
            if range_match:
                start_byte = int(range_match.group(1))
                end_group = range_match.group(2)
                if end_group:
                    end_byte = int(end_group)
        
        # 计算实际需要传输的内容长度
        content_length = end_byte - start_byte + 1
        
        # 定义生成器函数，用于流式传输文件内容
        def generate_content():
            with open(target_path, 'rb') as file:
                # 定位到起始位置
                file.seek(start_byte)
                
                # 已传输的字节数
                bytes_sent = 0
                
                # 读取并发送数据
                while bytes_sent < content_length:
                    # 计算本次应读取的字节数
                    chunk_size = min(buffer_size, content_length - bytes_sent)
                    
                    # 读取数据
                    data = file.read(chunk_size)
                    if not data:
                        break
                    
                    # 更新已发送字节数
                    bytes_sent += len(data)
                    
                    # 发送数据块
                    yield data
        
        # 创建响应对象
        response = Response(
            generate_content(),
            mimetype=mime_type,
            direct_passthrough=True  # 直接传递，不缓冲
        )
        
        # 设置响应头
        response.headers['Content-Disposition'] = f"inline; filename*=UTF-8''{quote(os.path.basename(target_path))}"
        response.headers['Accept-Ranges'] = 'bytes'
        response.headers['Content-Length'] = str(content_length)
        
        # 如果是范围请求，设置206状态码和Content-Range头
        if range_header:
            response.status_code = 206  # Partial Content
            response.headers['Content-Range'] = f'bytes {start_byte}-{end_byte}/{file_size}'
        else:
            # 全文请求，设置Content-Range头（可选）
            response.headers['Content-Range'] = f'bytes 0-{file_size-1}/{file_size}'
        
        return response